﻿
using EmperialApps.WeatherSpark.Data;
using Microsoft.WindowsAzure;
using Microsoft.WindowsAzure.ServiceRuntime;
using Microsoft.WindowsAzure.Storage;
using System.Diagnostics;

namespace EmperialApps.WeatherSpark.Service.Internal {

    /// <summary>Represents storage resources.</summary>
    internal sealed class StorageAccount {

        private readonly bool _isPrimaryInstance;
        private readonly SubscriptionsTableStore _subscriptions;
        private readonly ForecastInfoTableStore _forecastInfo;
        private readonly ForecastAggregator _aggregator;
        private readonly LocationQueueScheduler _scheduler;


        public static readonly StorageAccount Current = new StorageAccount( );

        private StorageAccount( ) {
            TraceEventType.Verbose.Trace( "Retrieving account..." );
            var instance = RoleEnvironment.CurrentRoleInstance;
            this._isPrimaryInstance = instance.FaultDomain == 0 && instance.UpdateDomain == 0;
            var account = CloudStorageAccount.Parse( CloudConfigurationManager.GetSetting( "StorageConnectionString" ) );

            TraceEventType.Verbose.Trace( "Initializing subscriptions store..." );
            this._subscriptions = new SubscriptionsTableStore( account );

            TraceEventType.Verbose.Trace( "Initializing forecast info store..." );
            this._forecastInfo = new ForecastInfoTableStore( account );

            TraceEventType.Verbose.Trace( "Initializing forecast aggregator..." );
            this._aggregator = new ForecastAggregator( account, this._forecastInfo, ForecastSource.NOAA, ForecastSource.YRNO );

            TraceEventType.Verbose.Trace( "Initializing location scheduler..." );
            this._scheduler = new LocationQueueScheduler( account, this._forecastInfo, this._isPrimaryInstance );

            TraceEventType.Verbose.Trace( "Storage initialization complete." );
        }


        public bool IsPrimaryInstance { get { return this._isPrimaryInstance; } }

        public SubscriptionsTableStore Subscriptions { get { return this._subscriptions; } }

        public ForecastInfoTableStore ForecastInfo { get { return this._forecastInfo; } }

        public ForecastAggregator Aggregator { get { return this._aggregator; } }

        public LocationQueueScheduler Scheduler { get { return this._scheduler; } }


        public void SendDownloadRequest( Coordinate location ) {
            this._scheduler.AddLocation( location );
        }

    }

}
